<?php
include 'includes/general.php';
include 'includes/slides.php';
include 'includes/widget.php';

//添加菜单
function add_menu_general() {
	add_menu_page('主题设置', '主题', 'administrator', 'general', 'bzg_general_control', 'dashicons-screenoptions', 100);
	add_submenu_page('general', '主题设置', '常规', 'administrator', 'general', 'bzg_general_control');
	add_submenu_page('general', '轮播图管理', '轮播', 'administrator', 'slides', 'bzg_slides_control');
}
add_action('admin_menu', 'add_menu_general');

//启用主题时执行
function bzg_theme_initi() {
	global $pagenow;
	if('themes.php' == $pagenow && isset($_GET['activated'])) {
		//执行代码
	}
}
add_action('load-themes.php', 'bzg_theme_initi');

function bzg_theme_setup() {
	//添加缩略图支持
	add_theme_support('post-thumbnails');

	//HTML5表单
	add_theme_support('html5', array(
		'search-form',
		'comment-form',
		'comment-list',
		'gallery',
		'caption',
		'script',
		'style',
	));

	// 自定义导航菜单
	register_nav_menus(
		array(
			'primary_nav' => '主导航',
			'footer_nav' => '页脚导航',
		)
	);
}
add_action('after_setup_theme', 'bzg_theme_setup');

//添加HTML编辑器自定义快捷标签按钮
function bzg_add_button_mce() {
	echo '<script type="text/javascript">
			QTags.addButton("pre", "pre", "<pre>", "</pre>");
		</script>';
}
add_action('after_wp_tiny_mce', 'bzg_add_button_mce');

//加载dashicons图标、CSS、JS
function bzg_load_scripts() {
	$hicolor = get_option('hicolor', 'red');
	wp_enqueue_style('bootcss', get_theme_file_uri('/assets/css/bootstrap.min.css'));
	wp_enqueue_style('dashicons', 'dashicons', 'bootcss');
	wp_enqueue_style('style', get_stylesheet_uri(), 'dashicons');
	wp_enqueue_style('hicolor', get_theme_file_uri('/assets/css/hicolor/') . $hicolor . '.css', 'style');
	wp_enqueue_script('jq', get_theme_file_uri('/assets/js/jquery.min.js'));
	wp_enqueue_script('popper', get_theme_file_uri('/assets/js/popper.min.js'), 'jq');
	wp_enqueue_script('bootjs', get_theme_file_uri('/assets/js/bootstrap.min.js'), 'popper');
	if(is_single()) {
		wp_enqueue_script('social', get_theme_file_uri('/assets/js/social.js'), 'bootjs');
		wp_localize_script('social', 'ajax_object', array(
			'ajax_url' => admin_url('admin-ajax.php')
		));
	}
}
add_action('wp_enqueue_scripts', 'bzg_load_scripts');

//Ajax Post Meta
function bzg_ajax_post_meta() {
	if(!isset($_POST['post_id']) || !isset($_POST['type'])) return;

	$types = ['add_likes', 'add_views', 'get_likes'];
	if(!in_array($_POST['type'], $types)) return;

	$post_id = (int) $_POST['post_id'];
	if(get_post_status($post_id) === false) return;

	list($do, $name) = explode('_', $_POST['type']);

	$value = get_post_meta($post_id, $name, true);
	if(!$value) $value = 0;
	if($do == 'add') {
		$value = $value+1;
		update_post_meta($post_id, $name, $value);
	}

	wp_send_json(array(
		'status' => 'success',
		'data' => $value,
	));
}
add_action('wp_ajax_post_meta', 'bzg_ajax_post_meta');
add_action('wp_ajax_nopriv_post_meta', 'bzg_ajax_post_meta');

//获取Post Meta
function bzg_post_meta($type='views') {
	global $post;
	$value = get_post_meta($post->ID, $type, true);
	echo $value ? $value : 0;
}

//阅读最多的文章
function bzg_get_hot_posts($limit=5, $time=360) {
	$args = array(
		'posts_per_page' => $limit,
		'order' => 'DESC',
		'post_status' => 'publish',
		'orderby'    => 'meta_value_num',
		'meta_key' => 'views', 
	);
	if($time) {
		$args['date_query'] = array(['after' => -$time . 'day']);
	}

	$cache_key = md5(join('', $args));
	$postlist = wp_cache_get($cache_key, 'hot_posts');
	if($postlist) return $postlist;
	$postlist = '';

	$postquery = get_posts($args);
	if(!$postquery) {
		unset($args['date_query']);
		$postquery = get_posts($args);
	}
	
	foreach($postquery as $post) {
		$views = get_post_meta($post->ID, 'views', true);
		$postlist .= '<li><a href="' . get_permalink($post->ID) . '" rel="bookmark">' . $post->post_title . '</a><span class="views">阅读 ' . $views . '</span></li>';
	}

	wp_cache_set($cache_key, $postlist, 'hot_posts', $time*86400);
	
	wp_reset_postdata();
	return $postlist;
}

//获取点赞最多文章
function bzg_get_like_posts($limit=5, $time=360) {
	$args = array(
		'posts_per_page' => $limit,
		'order' => 'DESC',
		'post_status' => 'publish',
		'orderby'    => 'meta_value_num',
		'meta_key' => 'likes',
	);
	if($time) {
		$args['date_query'] = array(['after' => -$time . 'day']);
	}

	$cache_key = md5(join('', $args));
	$postlist = wp_cache_get($cache_key, 'like_posts');
	if($postlist) return $postlist;
	$postlist = '';

	$postquery = get_posts($args);
	if(!$postquery) {
		unset($args['date_query']);
		$postquery = get_posts($args);
	}
	foreach($postquery as $post) {
		$likes = get_post_meta($post->ID, 'likes', true);
		$postlist .= '<li><a href="' . get_permalink($post->ID) . '" rel="bookmark">' . $post->post_title . '</a><span class="likes">' . $likes . '人喜欢</span></li>';
	}

	wp_cache_set($cache_key, $postlist, 'like_posts', $time*86400);

	wp_reset_postdata();
	return $postlist;
}

//分类、标签SEO标题
function bzg_add_cat_metabox() {
	echo '<div class="form-field">
			<label for="seo-title">SEO标题</label>
			<input type="text" size="40" value="" id="seo-title" name="seo_title">
			<p>SEO标题只显示在Title标签中，不会在其他地方显示</p>
		</div>';
}
add_action('category_add_form_fields', 'bzg_add_cat_metabox');
add_action('post_tag_add_form_fields', 'bzg_add_cat_metabox');

function bzg_edit_cat_metabox($tag) {
	$value = get_term_meta($tag->term_id, 'seo_title', true);
	echo '<tr class="form-field">
			<th scope="row"><label for="seo-title">SEO标题</label></th>
			<td>
				<input type="text" size="40" value="' . $value . '" id="seo-title" name="seo_title" />
				<p class="description">SEO标题只显示在Title标签中，不会在其他地方显示</p>
			</td>
		</tr>';
}
add_action('category_edit_form_fields', 'bzg_edit_cat_metabox', 10, 1);
add_action('post_tag_edit_form_fields', 'bzg_edit_cat_metabox', 10, 1);

function bzg_update_metadata($term_id) {
	if(!isset($_POST['seo_title']) || !current_user_can('manage_categories')) return $term_id;
	$data = sanitize_text_field($_POST['seo_title']);
	update_term_meta($term_id, 'seo_title', $data);
}

function bzg_delete_metadata($term_id) {
	if(!current_user_can('manage_categories')) return $term_id;
	delete_term_meta($term_id, 'seo_title');
}
add_action('created_category', 'bzg_update_metadata', 10, 1);
add_action('edited_category', 'bzg_update_metadata', 10, 1);
add_action('delete_category', 'bzg_delete_metadata', 10, 1);

add_action('created_post_tag', 'bzg_update_metadata', 10, 1);
add_action('edited_post_tag', 'bzg_update_metadata', 10, 1);
add_action('delete_post_tag', 'bzg_delete_metadata', 10, 1);

//Title标题
function bzg_filter_title($title) {
	if(is_front_page()) {
		$home_title = get_option('home_title');
		if($home_title) {
			$title['title'] = $home_title;
			$title['tagline'] = '';
			$title['site'] = '';
		}
	}

	if(is_category() || is_tag()) {
		global $cat, $tag_id;
		if(is_tag()) $cat = $tag_id;
		$seo_title = get_term_meta($cat, 'seo_title', true);
		if($seo_title) {
			$title['title'] = $seo_title;
		}
	}

	if(is_author()) $title['title'] = '作者：' . $title['title'];

	return $title;
}
add_filter('document_title_parts', 'bzg_filter_title', 10, 1);

//Description标签
function bzg_seo_description() {
	global $post;

	$description = '';
	if(is_home()) $description = get_option('home_description');
	if((is_category() || is_tag()) && category_description()) {
		$description = wp_strip_all_tags(category_description(), true);
	}
	if(is_single() || is_page()) {
		if($post->post_excerpt) {
			$description = $post->post_excerpt;
		} else {
			$description = mb_substr(esc_html(wp_strip_all_tags($post->post_content, true)), 0, 200, 'utf-8');
		}
	}

	echo $description;
}

//Bootstrap菜单
function bzg_nav_class($classes) {
    foreach($classes as $key=>$val) {
    	switch($val) {
			case 'menu-item' :
				$classes[$key] = 'nav-item';
				break;
			case 'current-menu-item' :
				$classes[$key] = 'active';
				break;
			case 'current-menu-parent' :
				$classes[$key] = 'dropdown';
				break;
			case 'current_page_item' :
				unset($classes[$key]);
				break;
			case 'menu-item-object-custom' :
				unset($classes[$key]);
				break;
			case 'menu-item-type-custom' :
				unset($classes[$key]);
				break;
			case 'menu-item-type-taxonomy' :
				unset($classes[$key]);
				break;
			case 'menu-item-object-category' :
				unset($classes[$key]);
				break;
			case 'menu-item-type-post_type' :
				unset($classes[$key]);
				break;
			case 'menu-item-object-page' :
				unset($classes[$key]);
				break;
			case 'current-menu-ancestor' :
				unset($classes[$key]);
				break;
			case 'current_page_parent' :
				unset($classes[$key]);
				break;
			case 'current_page_ancestor' :
				unset($classes[$key]);
				break;
			case 'menu-item-has-children' :
				$classes[$key] = 'dropdown';
				break;
			default:
				
		}
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'bzg_nav_class', 10, 1);

function bzg_submenu_css_class($classes) {
	$classes[0] = 'dropdown-menu';
	return $classes;
}
add_filter('nav_menu_submenu_css_class', 'bzg_submenu_css_class', 10, 1);

function bzg_nav_menu_link_attributes($atts, $item, $args, $depth) {
	$atts['class'] = 'nav-link';
	if(array_search('menu-item-has-children', $item->classes) !== false) {
		$atts['class'] .= ' dropdown-toggle';
		$atts['id'] = '';
		$atts['href'] = '#';
		$atts['data-toggle'] = 'dropdown';
		$atts['aria-haspopup'] = 'true';
		$atts['aria-expanded'] = 'false';
	}
	if($depth > 0) {
		$atts['class'] = 'dropdown-item';
	}
	return $atts;
}
add_filter('nav_menu_link_attributes', 'bzg_nav_menu_link_attributes', 10, 4);

//页面列表
function bzg_page_nav() {
	$pages = get_pages('hierarchical=0');
	if(!$pages) return;
	$list = array();
	foreach($pages as $page) {
		$link = get_permalink($page->ID);
		$list[] = '<a href="' . $link . '" rel="bookmark">' . $page->post_title . '</a>'; 
	}
	echo implode('<span> · </span>', $list);
}
//分类列表
function bzg_categories_nav() {
	global $cat;
	$class = is_home() ? ' active' : '';
	echo '<li class="menu-item-home nav-item' . $class . '"><a class="nav-link" href="' . get_option('url') . '" rel="home">首页</a></li>';
	$categories = get_categories();
	if(!$categories) return;

	foreach($categories as $categorie) {
		if($categorie->parent) continue;
		$class = $cat == $categorie->cat_ID ? ' active' : '';
		echo '<li class="nav-item' . $class . '"><a class="nav-link" href="' . get_category_link($categorie->cat_ID) . '">' . $categorie->name . '</a></li>';
	}
}
//评论摘要数量
function bzg_comment_excerpt_length() {
	return 50;
}
add_filter('comment_excerpt_length', 'bzg_comment_excerpt_length');
//过滤归档页标题
function bzg_archive_title_prefix() {
	return '';
}
add_filter('get_the_archive_title_prefix', 'bzg_archive_title_prefix');
//边栏图片加属性
function bzg_media_image_instance($instance) {
	$instance['size'] = 'medium_large';
	$instance['link_target_blank'] = true;
	//$instance['link_rel'] = 'noopener noreferrer nofollow';
	return $instance;
}
add_filter('widget_media_image_instance', 'bzg_media_image_instance', 10, 1);

?>
